var app = getApp()
var appData = app.globalData
var i, j, k     //点中桌下标
var ii, jj, kk  //换桌模式下的点中桌下标
var c = require('../../js/common.js')
var that
var _this
Page({
   data: {
      tableList: null,    //餐桌列表
      tableIsShowArr: null,//餐桌分类(分区）是否显示
      clickTable: null,   //当前点中餐桌
      clickEvent: -1,
      do_mode: '',      //点击桌的两种操作模式（1正常，2：change换桌)
      statusArr: [//餐桌status可作为下标,然后循环调用按钮值
         ['点菜', '取消关桌'],                 //0是关桌状态
         ['点菜', '留座', '关桌'],             //1是空桌
         ['加菜', '查看菜单', '结账', '换桌', '取消开桌'],  //2是开桌
         ['点菜', '取消留座']                  //3是留座
      ],
      msg: [],
      msg_show: 0,
      btnArrIsShow: false,
      uid: ''
   },

   onLoad: function () {
      var that = this
      _this=this
      var user = appData.shopInfo
      this.data.uid = user.Biz_ID
      wx.setNavigationBarTitle({
         title: user.Biz_Name + '前台',
      })
      console.log("【user】===", user)
      //开桌、加菜后通知更新界面
      app.setNoticeTableList(function (updateData) {
         var U = updateData
         if (U == 'reload') {
            that.onLoad()
         } else {
            if (U.cateId) { //如果是分类变更
               that.updateTableCate(U)
            } else {
               var table = t.data.tableList[i].list[j][k]
               console.log('通知更新界面U：', U, '通知更新table：', table)
               that.updateTableList(table, U)
            }
         }
      })
      // 获取餐桌信息
      var param = {
         Biz_ID: user.Biz_ID
      }
      app.getJsonData('table/Tmg/getAllTableList', param, function (tableListData) {
         console.log('【返回餐桌信息】===', tableListData)
         that.handleTableList(tableListData)
      })
      this.initWebsocket()
   },

   handleTableList: function (data) {
      if (data.code == 0) {
         var obj = data.data
         this.setAppTableCateArr(obj)
         var isShow = []
         isShow.push(true)
         for (var i = 0; i < obj.length; i++) {
            isShow.push(true)
         }
         this.setData({
            tableIsShowArr: isShow,
            tableList: data.data,
         })
      }
   },

   initWebsocket: function () {
      var t = this
      app.readyWebsocket(function (cb) {
         console.log('【全局appData前】==' + appData.isWsSender, appData, '【home收到wss回调callback】', cb)
         if (appData.isWsSender == 0) {
            if (cb.i) {
               var tab = t.data.tableList[cb.i].list[cb.j][cb.k]
            } else {
               var tab = t.searchTable(cb.msg[0])
            }
            t.updateTableList(tab, cb.msg)
            app.playMp3(cb.msg[1])
         } else {
            appData.isWsSender = 0
         }
         console.log('【全局appData后】==' + appData.isWsSender, appData)
         t.setMsg(cb)
      })
   },

   setMsg: function (N) {
      this.data.msg.unshift(N.setMsg + '  ' + c.getNowTime())
      this.setData({
         msg: this.data.msg,
         msg_show: 1
      })
      console.log('this.data.msg==', this.data.msg)
   },

   readySendSocket: function (updateData) {
      var td = this.data
      var is_c = td.do_mode == 'change'
      var _msg
      var tab = td.tableList[i].list[j][k]
      if (td.clickEvent == 'change') {
         var tab2 = td.tableList[ii].list[jj][kk]
         _msg = tab.fenlei + tab.zhuo + '桌换到了' + tab2.fenlei + tab2.zhuo + '桌'
      } else {
         _msg = tab.fenlei + tab.zhuo + '桌' + td.clickEvent
      }
      var m = {
         msg: updateData,
         i: is_c ? ii : i,
         j: is_c ? jj : j,
         k: is_c ? kk : k,
         setMsg: _msg
      }//i,j,k必须要传，接收方才知道要更新哪张桌子
      var json = {
         type: 'say',
         to_client_id: 'all',
         content: JSON.stringify(m)
      }
      var msg = JSON.stringify(json)
      appData.isWsSender = 1
      app.sendSocketMsg(msg)
   },

   searchTable: function (table_id) {
      var list = this.data.tableList
      for (var i = 0; i < list.length; i++) {
         var list_j = list[i].list
         for (var j = 0; j < list_j.length; j++) {
            var list_k = list_j[j]
            for (var k = 0; k < list_k.length; k++) {
               var tab = list_k[k]
               if (tab.Table_ID == table_id) {
                  return tab
               }
            }
         }
      }
   },

   updateTableList: function (table, newData) {
      //newData数组结构：0桌号, 1状态, 2订单号, 3订单价格, 4点菜数量
      table.status = newData[1]
      if (newData[4]) {//加菜，因接口未做这个数量的累加
         var num = table.foodNum + newData[4]
      } else {//除加菜
         var num = newData[4]
      }
      if (newData.length > 2) {
         table.orderid = newData[2]
         table.totalPrice = newData[3]//.toFixed(2)
         table.foodNum = num
         table.guestNum = newData[5]
      }
      this.setData({
         tableList: this.data.tableList
      })
   },

   updateTableCate: function (newCate) {
      var N = newCate
      var list = this.data.tableList
      var arr = this.data.tableIsShowArr
      var index = this.getIndex(N.cateId, list)
      if (N.notice == 'del') {
         list.splice(index, 1)
         arr.splice(index, 1)
      } else if (index == -1) {
         list.push(N)
         arr.push(arr[0])
      } else {
         list[index].cateName = N.cateName
         list[index].cateSort = N.cateSort
      }

      console.log('updateTableCate:list', list)
      this.setData({
         tableList: list,
         tableIsShowArr: arr
      })
      this.setAppTableCateArr(list)
   },

   getIndex: function (id, list) {
      for (var i = 0; i < list.length; i++) {
         if (list[i].cateId == id) {
            return i
         }
      }
      return -1//表示没有
   },

   cancelChange: function () {
      this.setData({ do_mode: '' })
   },
   //选桌点击 
   tableClick: function (e) {
      var indexs = e.currentTarget.id.split(':');
      if (this.data.do_mode != 'change') {//非换桌模式下
         i = indexs[0]
         j = indexs[1]
         k = indexs[2]
         this.setData({
            btnArrIsShow: true,
            clickTable: this.data.tableList[i].TableList[j][k]
         })
      } else {//换桌模式
         ii = indexs[0]
         jj = indexs[1]
         kk = indexs[2]
         var newTable = this.data.tableList[ii].TableList[jj][kk]
         if (newTable.Table_ID == this.data.clickTable.Table_ID) {
            this.setData({ do_mode: '' })
         } else {
            this.eventHandle(newTable, 'change')
            this.setData({ clickTable: newTable })
         }
      }
   },
   // 点击弹框按钮效果
   tableEvent: function (e) {
      var table = this.data.tableList[i].TableList[j][k]
      var index = e.currentTarget.id
      console.log("【点击获取】===",index)
      var t = this
      var msg
      if (table.status == 0) {//状态:关桌
         if (index == 0) {
            msg = '开席了'
            this.openTable(table)
         } else if (index == 1) {//
            msg = '取消了关桌'
            this.eventHandle(table, 'open')
         }
      } else if (table.status == 1) {//状态:空桌
         if (index == 0) {
            msg = '开席了'
            this.openTable(table)
         } else if (index == 1) {
            msg = '留座了'
            this.eventHandle(table, 'keep')
         } else if (index == 2) {
            msg = '关桌了'
            this.eventHandle(table, 'close')
         }
      } else if (table.status == 2) {//状态开桌
         if (index == 0) {
            msg = '加菜了'
            this.openTable(table)
         } else if (index == 1) {
            msg = '查看菜单'
            let tableStr = JSON.stringify(this.data.clickTable)
            wx.navigateTo({
               url: '/pages/01homePage/06order/manage?table=' + tableStr
            })
         } else if (index == 2) {
            msg = '去结账'
            let tableStr = JSON.stringify(this.data.clickTable)
            wx.navigateTo({
               url: '/pages/01homePage/07checkout/checkout?table=' + tableStr
            })
         } else if (index == 3) {
            msg = 'change'
            this.setData({ do_mode: 'change' })
         } else if (index == 4) {
            app.confirm('重要提示', '确认取消开桌吗？', '确定取消', function (res) {
               if (res) {
                  msg = '取消了开桌'
                  t.data.clickEvent = msg//因为点了确定，停止了往下运行该方法,所以这里重输一下
                  t.eventHandle(table, 'cancel')
               }
            })
         }
      } else if (table.status == 3) {//状态留座
         if (index == 0) {
            msg = '开席了'
            this.openTable(table)
         } else if (index == 1) {
            msg = '取消了留座'
            this.eventHandle(table, 'open')
         }
      }
      this.setData({
         btnArrIsShow: false,
         clickEvent: msg
      })
      console.log('this.data.clickEvent==' + this.data.clickEvent)
   },
   //开桌、加菜
   openTable: function (table) {
      let tableStr = JSON.stringify(table)
      wx.navigateTo({
         url: '/pages/01homePage/02openTable/openTable?table=' + tableStr
      })
   },
   //处理当前点中桌的事件参数：(桌，指令)
   eventHandle: function (table, command) {
      // console.log("【获取传递的参数】===",command)
      var param = {}
      var data = {
         // this.data.uid
         Biz_ID: appData.shopInfo.Biz_ID,
         Table_ID: table.Table_ID
      }
      var tab = this.data.tableList[i].TableList[j][k]//原点中桌
      if (command == 'change') {
         param.Table_ID1 = tab.Table_ID
         param.Table_ID2 = table.Table_ID
         // 执行换桌
         this.ChangeTable(table, tab, param, command)
      } else if (command == 'cancel') {
         // param.orderid = table.orderid
      } else if (command == 'keep') {
         data.status = 3
         // 执行桌指令
         this.ChangeTableStatus(table, tab, data, command)
      } else if (command == 'open') {
         data.status = 1
         // 执行桌指令
         this.ChangeTableStatus(table, tab, data, command)
      }
   },
   // 桌，指令
   ChangeTableStatus(table, tab, data, command) {
      app.getJsonData('table/Tmg/changeTableStatus', data, function (res) {
         // console.log('关桌、留座时res.data：', res.data)
         if (res.code == 0) {
            appData.isWsSender = 1
            if (command == 'cancel') {
               //当前桌置空
               var noti = [tab.Table_ID, 1, '', 0, 0, 0]
               console.log('换掉时当前桌置空noti：', notiNew)
               _this.updateTableList(_this.data.tableList[i].TableList[j][k], noti)
               // _this.readySendSocket(noti)
            } else {
               console.log('关桌、留座时res.data：', res.data)
               _this.updateTableList(table, res.data)
               // _this.readySendSocket(res.data)
            }
         }
      })
   },
   // 换桌状态
   ChangeTable(table, tab, param, command) {
      app.getJsonData('table/Tmg/changeTable', param, function (res) {
         if (command == 'change') {
            var notiNew = [table.Table_ID, 2, tab.orderid, tab.totalPrice, tab.foodNum, tab.guestNum]
            console.log('换掉时notiNew：', notiNew)
            _this.updateTableList(_this.data.tableList[ii].TableList[jj][kk], notiNew)
            // _this.readySendSocket(notiNew)
            _this.setData({ do_mode: '' })
         }
         //当前桌置空
         var noti = [tab.Table_ID, 1, '', 0, 0, 0]
         console.log('换掉时当前桌置空noti：', notiNew)
         _this.updateTableList(_this.data.tableList[i].TableList[j][k], noti)
         // _this.readySendSocket(noti)
      })
   },
   maskHide: function () {
      this.setData({
         btnArrIsShow: false
      })
   },

   pickerClick: function (e) {
      this.setData({ //选中picker
         index2: e.detail.value
      })
   },
   //存到全局变量中
   setAppTableCateArr: function (obj) {
      var table_cateArr = []
      for (var i = 0; i < obj.length; i++) {
         var tablbeCate = {
            cateId: obj[i].cateId,
            cateName: obj[i].cateName,
            cateSort: obj[i].cateSort,
         }
         table_cateArr.push(tablbeCate)
      }
      appData.tableCateArr = table_cateArr
   },

   clickCate: function (e) {
      var num = this.data.tableIsShowArr.length
      var index = Number(e.currentTarget.id)
      var isShow = []

      for (var i = 0; i < num; i++) {
         if (index == 0) {
            isShow.push(true)
         } else {
            isShow.push(index == i ? true : false)
         }
      }
      this.setData({
         tableIsShowArr: isShow
      })
      console.log(isShow)
      console.log('isShow')
   },

   onPullDownRefresh: function () {
      this.reload('下')
   },

   onReachBottom: function () {
      this.reload('上')
   },

   reload: function (msg) {
      app.toast(msg + '拉刷新了')
      this.onLoad()
   },
   /**
    * 生命周期函数--监听页面初次渲染完成
    */
   onReady: function () {
      console.log('生命周期函数--监听页面初次渲染完成')
   },
   /**
    * 生命周期函数--监听页面显示
    */
   onShow: function () {
      console.log('生命周期函数--监听页面显示appData', appData)
      var appUser = appData.shopInfo
      if (appUser.Biz_ID != this.data.uid) {
         this.setData({
            msg: [],
            msg_show: 0
         })
         console.log('开始重载')
         this.onLoad()
      } else if (appData.client_id == '') {
         this.initWebsocket()
      }
   },
   /**
    * 生命周期函数--监听页面隐藏
    */
   onHide: function () {
      console.log('生命周期函数--监听页面隐藏')
   },
   /**
    * 生命周期函数--监听页面卸载
    */
   onUnload: function () {
      console.log('生命周期函数--监听页面卸载')
   },

   showMsg: function () {
      this.setData({
         msg_show: this.data.msg_show ? 0 : 1
      })
   },

   onShareAppMessage: function () {
      var userInfoStr = JSON.stringify(appData.guestInfo)
      return {
         title: appData.guestInfo.name + '邀请您来【桥掌柜】当掌柜',
         path: '/pages/00login/login?str=' + userInfoStr
      }
   }
})